package com.example.mrzhou.lvmm.commom.utils;

import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.OnTabSelectListener;

import java.util.List;

/**
 * Created by Mr.zhou on 2016/10/14.
 */

public final class BottomBarTabUtils implements OnTabSelectListener {

    private FragmentManager manager;
    private FragmentTransaction transaction;
    private BottomBar bottomBar;
    private List<Fragment> fragments;
    private int layoutId;
    private static BottomBarTabUtils bottomBarTabUtils = null;

    private BottomBarTabUtils() {

    }

    public static BottomBarTabUtils getInstance() {
        if (bottomBarTabUtils == null) {
            bottomBarTabUtils = new BottomBarTabUtils();
        }
        return bottomBarTabUtils;
    }


    public void tabUtils(FragmentManager manager, BottomBar bottomBar, List<Fragment> fragments, int layoutId) {
        this.manager = manager;
        this.bottomBar = bottomBar;
        this.fragments = fragments;
        this.layoutId = layoutId;
        bottomBar.setOnTabSelectListener(this);
    }

    @Override
    public void onTabSelected(@IdRes int tabId) {
        for (int i = 0; i < bottomBar.getTabCount(); i++) {
            transaction = manager.beginTransaction();
            if (bottomBar.getTabAtPosition(i).getId() == tabId) {
                Fragment fragment = fragments.get(i);
                for (int i1 = 0; i1 < fragments.size(); i1++) {
                    if (i1 == i) {
                        if (!fragment.isAdded()) {
                            transaction.add(layoutId, fragment);
                        }
                        transaction.show(fragment);
                    } else {
                        transaction.hide(fragments.get(i1));
                    }
                }
            }
            transaction.commit();
        }
    }
}
